<template>
  <view class="product-detail-page">
    <view class="page-header">
      <text class="page-title">产品详情</text>
      <view class="header-actions">
        <button class="btn btn-default" @click="handleBack">返回</button>
        <button class="btn btn-primary" @click="handleEdit">编辑</button>
        <button class="btn btn-danger" @click="handleDelete">删除</button>
      </view>
    </view>

    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else class="detail-content">
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">基本信息</text>
          <view :class="['status-badge', getStatusClass(product.status)]">
            {{ getStatusText(product.status) }}
          </view>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">产品名称</text>
            <text class="value">{{ product.product_name || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">产品代码</text>
            <text class="value">{{ product.product_code || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">产品类型</text>
            <text class="value">{{ getProductTypeText(product.product_type) }}</text>
          </view>
          
          <view v-if="product.description" class="detail-row vertical">
            <text class="label">产品描述</text>
            <text class="value">{{ product.description }}</text>
          </view>
          
          <view v-if="getImageUrl(product.image)" class="detail-row vertical">
            <text class="label">产品图片</text>
            <image 
              class="product-image" 
              :src="getImageUrl(product.image)" 
              mode="aspectFit"
              @click="previewImage(getImageUrl(product.image))"
            />
          </view>
        </view>
      </view>

      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">价格与库存</text>
          <view v-if="isStockLow" class="warning-badge">库存预警</view>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">价格</text>
            <text class="value highlight">¥{{ product.price || 0 }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">库存数量</text>
            <text :class="['value', isStockLow ? 'warning' : '']">{{ product.stock_quantity || 0 }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">预警阈值</text>
            <text class="value">{{ product.stock_alert_threshold || 0 }}</text>
          </view>
        </view>
      </view>

      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">供应商信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">供应商</text>
            <text class="value">{{ product.supplier || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">批号</text>
            <text class="value">{{ product.batch_no || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">过期日期</text>
            <text class="value">{{ formatDate(product.expiry_date) }}</text>
          </view>
        </view>
      </view>

      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">时间信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">创建时间</text>
            <text class="value">{{ formatTime(product.create_time) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">更新时间</text>
            <text class="value">{{ formatTime(product.update_time) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

const loading = ref(true)
const productId = ref('')
const product = reactive({
  product_name: '',
  product_code: '',
  product_type: 1,
  description: '',
  image: '',
  price: 0,
  stock_quantity: 0,
  stock_alert_threshold: 0,
  supplier: '',
  batch_no: '',
  expiry_date: null,
  status: 1,
  create_time: null,
  update_time: null
})

const isStockLow = computed(() => {
  return product.stock_quantity <= product.stock_alert_threshold
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  productId.value = currentPage.options.id || ''
  
  if (!productId.value) {
    uni.showToast({ title: '缺少产品ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/products/list' })
    }, 1500)
    return
  }
  
  await loadProductData()
  loading.value = false
})

async function loadProductData() {
  try {
    // 调用云对象方法获取产品信息
    const productsObj = uniCloud.importObject('dh-products')
    const result = await productsObj.getProductById(productId.value)
    
    if (result.code === 200 && result.data) {
      Object.assign(product, result.data)
    } else {
      throw new Error(result.message || '产品不存在')
    }
  } catch (err) {
    console.error('加载产品数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/products/list' })
    }, 1500)
  }
}

function getProductTypeText(type) {
  const types = {
    1: '药品',
    2: '医疗器材',
    3: '其他'
  }
  return types[type] || '未知'
}

function getStatusText(status) {
  const statusMap = {
    1: '在售',
    2: '停售',
    3: '禁用'
  }
  return statusMap[status] || '未知'
}

function getStatusClass(status) {
  const classMap = {
    1: 'status-active',
    2: 'status-inactive',
    3: 'status-disabled'
  }
  return classMap[status] || ''
}

function formatDate(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

function getImageUrl(imageData) {
  if (!imageData) return ''
  if (typeof imageData === 'string') return imageData
  if (typeof imageData === 'object' && imageData.url) return imageData.url
  if (Array.isArray(imageData) && imageData.length > 0) {
    const first = imageData[0]
    return typeof first === 'string' ? first : (first.url || '')
  }
  return ''
}

function formatTime(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

function previewImage(url) {
  if (!url) return
  uni.previewImage({
    urls: [url],
    current: url
  })
}

function handleBack() {
  uni.redirectTo({ url: '/pages/business/products/list' })
}

function handleEdit() {
  uni.redirectTo({ url: `/pages/business/products/edit?id=${productId.value}` })
}

function handleDelete() {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个产品吗？此操作不可撤销。',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '删除中...' })
          // 调用云对象方法软删除产品
          const productsObj = uniCloud.importObject('dh-products')
          const result = await productsObj.deleteProduct(productId.value, '详情页删除')
          uni.hideLoading()
          if (result.code === 200) {
            uni.showToast({ title: result.message || '删除成功', icon: 'success' })
          } else {
            uni.showToast({ title: result.message || '删除失败', icon: 'none' })
            return
          }
          setTimeout(() => {
            uni.redirectTo({ url: '/pages/business/products/list' })
          }, 1500)
        } catch (err) {
          console.error('删除失败:', err)
          uni.hideLoading()
          uni.showToast({ title: err.message || '删除失败', icon: 'none' })
        }
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.product-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.page-header {
  background: #fff;
  padding: 30rpx 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
}

.btn {
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
  min-width: 100rpx;
  text-align: center;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
  
  &.btn-danger {
    background: #ff3b30;
    color: #fff;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .btn {
    flex: 1;
    min-width: 0;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.detail-content {
  flex: 1;
  padding: 20rpx;
}

.detail-card {
  background: #fff;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  background: #fafafa;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.status-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  
  &.status-active {
    background: #e8f5e9;
    color: #2e7d32;
  }
  
  &.status-inactive {
    background: #fff3e0;
    color: #e65100;
  }
  
  &.status-disabled {
    background: #fce4ec;
    color: #c2185b;
  }
}

.warning-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  background: #fff3e0;
  color: #e65100;
}

.card-body {
  padding: 32rpx;
}

.detail-row {
  display: flex;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &.vertical {
    flex-direction: column;
  }
}

.label {
  font-size: 28rpx;
  color: #999;
  min-width: 180rpx;
  margin-bottom: 8rpx;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  word-break: break-all;
  
  &.highlight {
    font-size: 36rpx;
    font-weight: bold;
    color: #007aff;
  }
  
  &.warning {
    color: #e65100;
    font-weight: bold;
  }
}

.product-image {
  width: 100%;
  max-width: 600rpx;
  height: 320rpx;
  border-radius: 8rpx;
  margin-top: 16rpx;
}
</style>
